import Vue from "vue";
import Vuex from "vuex";
import { loginApi, logoutApi, getUserInfoApi } from "@/api/auth";
import { getWebConfigApi } from "@/api/site";
import { getToken, setToken, removeToken } from "@/utils/cookie";
import music from "./modules/music";

Vue.use(Vuex);
export default new Vuex.Store({
  modules: {
    music,
  },
  state: {
    userInfo: sessionStorage.getItem("user")
      ? JSON.parse(sessionStorage.getItem("user"))
      : null,
    webSiteInfo: {
      showList: [],
    },
    token: getToken() || "",
    searchVisible: false,
    mobileMenuVisible: false,
    visitorAccess: 0,
    siteAccess: 0,
    isLoading: false,
    loadingTexts: [],
    notice: null,
    user: null,
    isLogin: false,
    currentArticle: null,
    loadingTarget: null,
    contentReady: false,
    loadingStartTime: 0,
    loadingConfig: {
      post: 1200,
      moments: 1000,
      photos: 1500,
      default: 600,
    },
  },
  mutations: {
    SET_USER(state, user) {
      state.user = user;
      state.isLogin = !!user;
    },
    setSiteInfo(state, info) {
      state.webSiteInfo = info;
    },
    SET_TOKEN(state, token) {
      state.token = token;
      setToken(token);
    },
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo;
      sessionStorage.setItem("user", JSON.stringify(userInfo));
    },
    SET_CURRENT_ARTICLE(state, article) {
      state.currentArticle = article;
    },
    SET_SEARCH_VISIBLE(state, visible) {
      state.searchVisible = visible;
    },
    SET_MOBILE_MENU_VISIBLE(state, visible) {
      state.mobileMenuVisible = visible;
    },
    setMobileMenuVisible(state, value) {
      state.mobileMenuVisible = value;
    },
    setVisitorAccess(state, value) {
      state.visitorAccess = value;
    },
    setSiteAccess(state, value) {
      state.siteAccess = value;
    },
    SET_LOADING(state, status) {
      state.isLoading = status;
      if (!status) {
        state.contentReady = false;
      }
    },
    SET_LOADING_TEXTS(state, texts) {
      state.loadingTexts = texts || [];
    },
    SET_NOTICE(state, notice) {
      state.notice = notice;
    },
    SET_LOADING_TARGET(state, target) {
      state.loadingTarget = target;
    },
    SET_CONTENT_READY(state, ready) {
      state.contentReady = ready;
    },
    SET_LOADING_START_TIME(state, time) {
      state.loadingStartTime = time;
    },
  },
  actions: {
    /**
     * 设置公告信息
     */
    setNotice({ commit }, notice) {
      commit("SET_NOTICE", notice);
    },

    /**
     * 设置站点信息
     */
    async setSiteInfo({ commit }) {
      try {
        const res = await getWebConfigApi();
        commit("setSiteInfo", res.data);
      } catch (error) {
        console.error("获取站点信息失败:", error);
      }
    },
    /**
     * 获取用户信息
     */
    async getUserInfo({ commit }) {
      if (getToken()) {
        const res = await getUserInfoApi();
        commit("SET_USER_INFO", res.data);
      }
    },

    /**
     * 登录
     */
    async loginAction({ commit }, loginData) {
      try {
        const res = await loginApi(loginData);
        if (res.data) {
          commit("SET_TOKEN", res.data.token);
          commit("SET_USER_INFO", res.data);
          commit("SET_USER", res.data);
          return Promise.resolve(res);
        }
        return Promise.reject(res);
      } catch (error) {
        return Promise.reject(error);
      }
    },

    /**
     * 退出登录
     */
    async logout({ commit }) {
      await logoutApi();
      removeToken();
      commit("SET_USER_INFO", null);
      commit("SET_USER", null);
    },

    /**
     * 显示加载状态
     * @param {String} target - 加载目标类型（可选）
     */
    showLoading({ commit }, target = "default") {
      commit("SET_LOADING_TARGET", target);
      commit("SET_CONTENT_READY", false);
      commit("SET_LOADING_START_TIME", Date.now());
      commit("SET_LOADING", true);

      // 调试日志
      console.log(`Loading started for target: ${target}`);
    },

    /**
     * 隐藏加载状态
     * 智能判断是否应该结束加载状态
     */
    hideLoading({ commit, state }) {
      // 标记内容已准备好
      commit("SET_CONTENT_READY", true);

      // 获取当前加载目标的最小显示时间
      const minTime =
        state.loadingConfig[state.loadingTarget] || state.loadingConfig.default;
      const elapsedTime = Date.now() - state.loadingStartTime;

      // 调试日志
      console.log(
        `Hiding loading, elapsed time: ${elapsedTime}ms, min time: ${minTime}ms`
      );

      if (elapsedTime >= minTime) {
        // 如果已经显示足够长时间，立即关闭
        console.log("Elapsed time sufficient, closing immediately");
        commit("SET_LOADING", false);
      } else {
        // 否则，等待最小显示时间后关闭
        console.log(`Waiting ${minTime - elapsedTime}ms before closing`);
        setTimeout(() => {
          console.log("Delayed closing triggered");
          commit("SET_LOADING", false);
        }, minTime - elapsedTime);
      }
    },

    /**
     * 通知内容已准备好
     * 由内容组件调用，表示实际数据已加载完成
     */
    contentReady({ dispatch, state }) {
      console.log("Content ready notification received in store");
      // 确保未处于loading状态或已有内容准备就绪时不重复处理
      if (state.isLoading && !state.contentReady) {
        dispatch("hideLoading");
      }
    },

    /**
     * 设置加载文本
     */
    setLoadingTexts({ commit }, texts) {
      commit("SET_LOADING_TEXTS", texts);
    },
  },
  getters: {
    getLoadingConfig: (state) => (target) => {
      return state.loadingConfig[target] || state.loadingConfig.default;
    },
  },
});
